/***************************************************************************
 *   Copyright (C) 2006 by Archimedes Projekt   *
 *   thelsb@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "dlgcommsettings.h"
#include <iostream>
#include <QtDebug>
#include <QSettings>

DlgCommSettings::DlgCommSettings(QString port,QWidget *parent,DlgCommSettings::uiType uiType)
    : QWidget(parent),
 m_uiType(uiType),
 m_serial(NULL),
 m_port(port) 
{
	//this->setAutoFillBackground(true);
	ui.setupUi(this);
  qDebug()<<"DlgCommSettings::DlgCommSettings()";
  std::cout<<"serial port:"<<port.toAscii().data()<<std::endl;
 
 
  ui.lblSync->setText("---");
  ui.btnConnect->replaceStatePixmap(PStyledButton::off_pressed,QPixmap(":images/serial/btn_connect_pressed.png"));
  ui.btnSettings->replaceStatePixmap(PStyledButton::off_pressed,QPixmap(":images/serial/btn_settings_pressed.png"));
  connect(ui.btnSettings,SIGNAL(clicked()),this,SIGNAL(sig_serialSettings()));
}

DlgCommSettings::DlgCommSettings(QWidget *parent ,DlgCommSettings::uiType uiType):
        QWidget(parent,Qt::Dialog|Qt::FramelessWindowHint),
        m_uiType(uiType)
{
  uiLarge.setupUi(this);
  this->setAutoFillBackground(true);
  uiLarge.setupUi(this);
  QPixmap bgpixmap = QPixmap(":images/serial/bkg_serial_large.png");
  if(bgpixmap.isNull()) std::cout<<"DlgCommSettings: null background pixmap"<<std::endl;
  QPalette p = this->palette();
  p.setBrush(this->backgroundRole(),QBrush(bgpixmap));
  this->setPalette(p);
  uiLarge.btnApply->replaceStatePixmap(PStyledButton::off_pressed,QPixmap(":images/serial/btn_apply_pressed.png"));
  uiLarge.btnBack->replaceStatePixmap(PStyledButton::off_pressed,QPixmap(":images/serial/btn_back_pressed.png"));
  uiLarge.listPort->setViewMode(QListView::ListMode);
  QListWidgetItem *temp=NULL;
  for(int i=0;i<8;++i)
  {
      temp = new QListWidgetItem(QString("/dev/ttyS%1").arg(i));
      temp->setSizeHint(QSize(uiLarge.listPort->width(),40));
      temp->setTextAlignment(Qt::AlignHCenter);
      uiLarge.listPort->addItem(temp);
  }
  
  temp = new QListWidgetItem(QString("110"));
  temp->setSizeHint(QSize(uiLarge.listSpeed->width(),30));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listSpeed->addItem(temp);
  temp = new QListWidgetItem(QString("300"));
  temp->setTextAlignment(Qt::AlignHCenter);
  temp->setSizeHint(QSize(uiLarge.listSpeed->width(),30));
  uiLarge.listSpeed->addItem(temp);
  for(int i=1200;i<38401;i*=2)
  {
      temp = new QListWidgetItem(QString("%1").arg(i));
      temp->setSizeHint(QSize(uiLarge.listPort->width(),32));
      temp->setTextAlignment(Qt::AlignHCenter);
      uiLarge.listSpeed->addItem(temp);
  }
  
  for(int i=57600;i<921601;i*=2)
  {
      temp = new QListWidgetItem(QString("%1").arg(i));
      temp->setSizeHint(QSize(uiLarge.listPort->width(),32));
      temp->setTextAlignment(Qt::AlignHCenter);
      uiLarge.listSpeed->addItem(temp);
  }
  for(int i=5;i<9;i++)
  {
      temp = new QListWidgetItem(QString("%1").arg(i));
      temp->setSizeHint(QSize(uiLarge.listDataBits->width(),32));
      temp->setTextAlignment(Qt::AlignHCenter);
      uiLarge.listDataBits->addItem(temp);
  }
  temp = new QListWidgetItem(QString("%1").arg(1));
  temp->setSizeHint(QSize(uiLarge.listStopBits->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listStopBits->addItem(temp);
  temp = new QListWidgetItem(QString("%1").arg(1.5));
  temp->setSizeHint(QSize(uiLarge.listStopBits->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listStopBits->addItem(temp);
  temp = new QListWidgetItem(QString("%1").arg(2));
  temp->setSizeHint(QSize(uiLarge.listStopBits->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listStopBits->addItem(temp);
  temp = new QListWidgetItem(QString("None"));
  temp->setSizeHint(QSize(uiLarge.listParity->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listParity->addItem(temp);
  temp = new QListWidgetItem(QString("Odd"));
  temp->setSizeHint(QSize(uiLarge.listParity->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listParity->addItem(temp);
  temp = new QListWidgetItem(QString("Even"));
  temp->setSizeHint(QSize(uiLarge.listParity->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listParity->addItem(temp);
  temp = new QListWidgetItem(QString("Marker"));
  temp->setSizeHint(QSize(uiLarge.listParity->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listParity->addItem(temp);
  temp = new QListWidgetItem(QString("Blank"));
  temp->setSizeHint(QSize(uiLarge.listParity->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listParity->addItem(temp);
  temp = new QListWidgetItem(QString("None"));
  temp->setSizeHint(QSize(uiLarge.listFlow->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listFlow->addItem(temp);
  temp = new QListWidgetItem(QString("Xon/Xoff"));
  temp->setSizeHint(QSize(uiLarge.listFlow->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listFlow->addItem(temp);
  temp = new QListWidgetItem(QString("Hardware"));
  temp->setSizeHint(QSize(uiLarge.listFlow->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listFlow->addItem(temp);
  temp = new QListWidgetItem(QString("HPSC"));
  temp->setSizeHint(QSize(uiLarge.listModule->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listModule->addItem(temp);
  temp = new QListWidgetItem(QString("CamCon"));
  temp->setSizeHint(QSize(uiLarge.listModule->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listModule->addItem(temp);
  temp = new QListWidgetItem(QString("ServCon"));
  temp->setSizeHint(QSize(uiLarge.listModule->width(),32));
  temp->setTextAlignment(Qt::AlignHCenter);
  uiLarge.listModule->addItem(temp);
  
    
    connect(uiLarge.btnApply,SIGNAL(clicked()),this,SLOT(saveConfig()));
    connect(uiLarge.btnApply,SIGNAL(clicked()),this,SIGNAL(sig_hide()));
    connect(uiLarge.btnBack,SIGNAL(clicked()),this,SLOT(hide()));
    connect(uiLarge.btnLoad,SIGNAL(clicked()),this,SLOT(loadConfig()));
    connect(uiLarge.listModule,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(loadConfig()));
    connect(uiLarge.listSpeed,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(updateSettigsLable()));
    connect(uiLarge.listParity,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(updateSettigsLable()));
    connect(uiLarge.listStopBits,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(updateSettigsLable()));
    connect(uiLarge.listPort,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(updateSettigsLable()));
    connect(uiLarge.listDataBits,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(updateSettigsLable()));

  
  
}


DlgCommSettings::~DlgCommSettings()
{
}

/*!
    \fn DlgCommSettings::setFlowControl(FlowControlType flow)
 */
void DlgCommSettings::setFlowControl(FlowType flow)
{
	m_flow = flow;
	if(m_serial)
	m_serial->setFlowControl(flow);
}


/*!
    \fn DlgCommSettings::setBaudRate(BaudRateType baud)
 */
void DlgCommSettings::setBaudRate(BaudRateType baud)
{
	m_baud = baud;
	if(m_serial)
	m_serial->setBaudRate(baud);
}

/*!
    \fn DlgCommSettings::setDataBits(DataBitsType bits)
 */
void DlgCommSettings::setDataBits(DataBitsType dataBits)
{
	m_dataBits = dataBits;
	if(m_serial)
		m_serial->setDataBits(dataBits);
}

/*!
    \fn DlgCommSettings::setParity(ParityType parity)
 */
void DlgCommSettings::setParity(ParityType parity)
{
	m_parity = parity;
	if(m_serial)
		m_serial->setParity(parity);
}

/*!
    \fn DlgCommSettings::setStopBits(StopBitsType stopBits)
 */
void DlgCommSettings::setStopBits(StopBitsType stopBits)
{
	m_stopBits = stopBits;
	if(m_serial)
		m_serial->setStopBits(stopBits);
}

/*!
    \fn DlgCommSettings::setPort(const QString &port)
 */
void DlgCommSettings::setPort(const QString &port)
{
	m_port = port;
}

/*!
    \fn DlgCommSettings::initSerial()
 */
void DlgCommSettings::initSerial()
{
	if(m_serial)
	{
		m_serial->setBaudRate(m_baud);
		m_serial->setDataBits(m_dataBits);
		m_serial->setParity(m_parity);
		m_serial->setStopBits(m_stopBits);
		m_serial->setFlowControl(m_flow);
	}

}


/*!
    \fn DlgCommSettings::serial()
 */
QextSerialPort * DlgCommSettings::serial()
{
	return m_serial;
}





/*!
    \fn DlgCommSettings::connectSerial()
 */
void DlgCommSettings::connectSerial()
{
  if(m_uiType==SMALL)
    if(m_serial)
    {
        if(m_serial->isOpen()) m_serial->close();	
        if(!m_serial->open())
                std::cout<<"DlgCommSettings coulnd not open serial port "<<m_port.toAscii().data()<<std::endl;
            else std::cout<<"DlgCommSettings opened "<<m_port.toAscii().data()<<std::endl;
    }
}


/*!
    \fn DlgCommSettings::updateConfig()
 */
void DlgCommSettings::saveConfig()
{
  qDebug()<<"DlgCommSettings::saveConfig()";
  if(m_uiType==LARGE)
  {
     QSettings settings("../../gss.conf",QSettings::IniFormat);
     if(uiLarge.listModule->currentItem()->text() == "HPSC")
     {
        settings.setValue("Serial_Ports/HPSC/port","/dev/"+uiLarge.listPort->currentItem()->text());
        settings.setValue("Serial_Ports/HPSC/speed",uiLarge.listSpeed->currentItem()->text());
        settings.setValue("Serial_Ports/HPSC/dataBits",uiLarge.listDataBits->currentItem()->text());
        settings.setValue("Serial_Ports/HPSC/stopBits",uiLarge.listStopBits->currentItem()->text());
        settings.setValue("Serial_Ports/HPSC/parity",uiLarge.listParity->currentItem()->text());
        settings.setValue("Serial_Ports/HPSC/flow",uiLarge.listFlow->currentItem()->text());
     }
     if(uiLarge.listModule->currentItem()->text() == "CamCon")
     {
         settings.setValue("Serial_Ports/CamCon/port","/dev/"+uiLarge.listPort->currentItem()->text());
       settings.setValue("Serial_Ports/CamCon/speed",uiLarge.listSpeed->currentItem()->text());
       settings.setValue("Serial_Ports/CamCon/dataBits",uiLarge.listDataBits->currentItem()->text());
       settings.setValue("Serial_Ports/CamCon/stopBits",uiLarge.listStopBits->currentItem()->text());
       settings.setValue("Serial_Ports/CamCon/parity",uiLarge.listParity->currentItem()->text());
       settings.setValue("Serial_Ports/CamCon/flow",uiLarge.listFlow->currentItem()->text());
     }
     if(uiLarge.listModule->currentItem()->text() == "ServCon")
     {
         settings.setValue("Serial_Ports/ServCon/port","/dev/"+uiLarge.listPort->currentItem()->text());
       settings.setValue("Serial_Ports/ServCon/speed",uiLarge.listSpeed->currentItem()->text());
       settings.setValue("Serial_Ports/ServCon/dataBits",uiLarge.listDataBits->currentItem()->text());
       settings.setValue("Serial_Ports/ServCon/stopBits",uiLarge.listStopBits->currentItem()->text());
       settings.setValue("Serial_Ports/ServCon/parity",uiLarge.listParity->currentItem()->text());
       settings.setValue("Serial_Ports/ServCon/flow",uiLarge.listFlow->currentItem()->text());
     }
  }
}


/*!
    \fn DlgCommSettings::loadConfig(MODULE module)
 */
void DlgCommSettings::loadConfig(MODULE module)
{
    qDebug()<<"DlgCommSettings::loadConfig(MODULE module)";
    QSettings settings("../../gss.conf",QSettings::IniFormat);  
    //QString port,speed,dataBits,stopBits,parity,flow;
    
        switch(module)
        {
        case HPSC:
            qDebug()<<"HPSC";
            if(m_uiType==LARGE)
                uiLarge.listModule->setCurrentRow(0);
            m_strPort     = settings.value("Serial_Ports/HPSC/port").toString();
            m_strSpeed    = settings.value("Serial_Ports/HPSC/speed").toString();
            m_strDataBits = settings.value("Serial_Ports/HPSC/dataBits").toString();
            m_strStopBits = settings.value("Serial_Ports/HPSC/stopBits").toString();
            m_strParity   = settings.value("Serial_Ports/HPSC/parity").toString();
            m_strFlow     = settings.value("Serial_Ports/HPSC/flow").toString();
            break;
        case CAMCON:
            qDebug()<<"CAMCON";
            if(m_uiType==LARGE)
                uiLarge.listModule->setCurrentRow(1);
            m_strPort     = settings.value("Serial_Ports/CamCon/port").toString();
            m_strSpeed    = settings.value("Serial_Ports/CamCon/speed").toString();
            m_strDataBits = settings.value("Serial_Ports/CamCon/dataBits").toString();
            m_strStopBits = settings.value("Serial_Ports/CamCon/stopBits").toString();
            m_strParity   = settings.value("Serial_Ports/CamCon/parity").toString();
            m_strFlow     = settings.value("Serial_Ports/CamCon/flow").toString();
            qDebug()<<"from config:"<<m_strSpeed<<" port"<<m_strPort;
            break;
        case SERVCON:
            qDebug()<<"SERVCON";
            if(m_uiType==LARGE)
                uiLarge.listModule->setCurrentRow(2);
            m_strPort     = settings.value("Serial_Ports/ServCon/port").toString();
            m_strSpeed    = settings.value("Serial_Ports/ServCon/speed").toString();
            m_strDataBits = settings.value("Serial_Ports/ServCon/dataBits").toString();
            m_strStopBits = settings.value("Serial_Ports/ServCon/stopBits").toString();
            m_strParity   = settings.value("Serial_Ports/ServCon/parity").toString();
            m_strFlow     = settings.value("Serial_Ports/ServCon/flow").toString();
            break;
            default: break;
            
        }

    if(m_uiType==LARGE)
    {  
        qDebug()<<"count:"<<uiLarge.listPort->count();
        for(int i=0;i<uiLarge.listPort->count();i++)
        {
            if(uiLarge.listPort->item(i)->text()==m_strPort)
               uiLarge.listPort->setCurrentRow(i);
        }

        for(int i=0;i<uiLarge.listSpeed->count();i++)
        {
            if(uiLarge.listSpeed->item(i)->text()==m_strSpeed)
                uiLarge.listSpeed->setCurrentRow(i);
        }

        for(int i=0;i<uiLarge.listDataBits->count();i++)
        {
            if(uiLarge.listDataBits->item(i)->text()==m_strDataBits)
                uiLarge.listDataBits->setCurrentRow(i);
        }

        for(int i=0;i<uiLarge.listStopBits->count();i++)
        {
            if(uiLarge.listStopBits->item(i)->text()==m_strStopBits)
                uiLarge.listStopBits->setCurrentRow(i);
        }

        for(int i=0;i<uiLarge.listParity->count();i++)
        {
            if(uiLarge.listParity->item(i)->text()==m_strParity)
                uiLarge.listParity->setCurrentRow(i);
        }

        for(int i=0;i<uiLarge.listFlow->count();i++)
        {
            if(uiLarge.listFlow->item(i)->text()==m_strFlow)
                uiLarge.listFlow->setCurrentRow(i);
        }
        
    }
    updateSettigsLable();
}


/*!
    \fn DlgCommSettings::loadConfig()
 */
void DlgCommSettings::loadConfig()
{
  if(m_uiType==LARGE)
  switch(uiLarge.listModule->currentRow())
  {
    case 0: loadConfig(HPSC);
    break;
    case 1: loadConfig(CAMCON);
    break;
    case 2: loadConfig(SERVCON);
    break;
    default: break;
  }
}


/*!
    \fn DlgCommSettings::updateSettigsLable()
 */
void DlgCommSettings::updateSettigsLable()
{
    qDebug()<<"DlgCommSettings::updateSettigsLable()";
    if(/*this->isVisible() &&*/ m_uiType==LARGE)
    {
        m_strStopBits = uiLarge.listStopBits->selectedItems()[0]->text();
        qDebug()<<"1";
        m_strSpeed = uiLarge.listSpeed->selectedItems()[0]->text();
        qDebug()<<"2";
        m_strDataBits = uiLarge.listDataBits->selectedItems()[0]->text();
        qDebug()<<"3";
        m_strParity = uiLarge.listParity->selectedItems()[0]->text();
        qDebug()<<"4";
        m_strFlow = uiLarge.listFlow->selectedItems()[0]->text();
        qDebug()<<"5";
        m_strPort = "/dev/"+uiLarge.listPort->selectedItems()[0]->text();
        qDebug()<<"6";
        m_strSettings = uiLarge.listSpeed->selectedItems()[0]->text()+","+uiLarge.listDataBits->currentItem()->text()+uiLarge.listParity->currentItem()->text().left(1)+uiLarge.listStopBits->currentItem()->text();
        qDebug()<<"7";
        uiLarge.lblSettings->setText(m_strSettings);
        qDebug()<<"8";
        uiLarge.lblPort->setText(m_strPort);
        qDebug()<<"9";
    }
    if(m_uiType==SMALL)
    {
        
        m_strSettings = m_strSpeed+","+m_strDataBits+m_strParity.left(1)+m_strStopBits;
        ui.lblPort->setText(m_strPort);
        qDebug()<<"settings:"<<m_strSettings;
        ui.lblSettings->setText(m_strSettings);
    }
    qDebug()<<"end";
}


/*!
    \fn DlgCommSettings::portLabel()
 */

const QString & DlgCommSettings::portStr() const
{
    return m_strPort;
}


/*!
    \fn DlgCommSettings::settingsLabelString()
 */
const QString & DlgCommSettings::settingsStr() const
{
    return m_strSettings;

}


/*!
    \fn DlgCommSettings::speedStr()
 */
const QString & DlgCommSettings::speedStr() const
{
    return m_strSpeed;
}


/*!
    \fn DlgCommSettings::dataBitsStr()
 */
const QString & DlgCommSettings::dataBitsStr() const
{
    return m_strDataBits;
}


/*!
    \fn DlgCommSettings::flowStr()
 */
const QString & DlgCommSettings::flowStr() const
{
    return m_strFlow;
}


/*!
    \fn DlgCommSettings::stopBitsStr()
 */
const QString & DlgCommSettings::stopBitsStr() const
{
    return m_strStopBits;
}


/*!
    \fn DlgCommSettings::parityStr()
 */
const QString & DlgCommSettings::parityStr() const
{
    return m_strParity;
}


/*!
    \fn DlgCommSettings::setSettingsStr(const QString &
 */
void DlgCommSettings::setSettingsStr(const QString &settings)
{
    m_strSettings = settings;
}


/*!
    \fn DlgCommSettings::setDataBitsStr(const QString &dataBits)
 */
void DlgCommSettings::setDataBitsStr(const QString &dataBits)
{
    m_strDataBits = dataBits;
}


/*!
    \fn DlgCommSettings::setFlowStr(const QString &flow)
 */
void DlgCommSettings::setFlowStr(const QString &flow)
{
    m_strFlow = flow;
}


/*!
    \fn DlgCommSettings::setParityStr(const QString &parity)
 */
void DlgCommSettings::setParityStr(const QString &parity)
{
    m_strParity = parity;
}


/*!
    \fn DlgCommSettings::setPortStr(const QString &port)
 */
void DlgCommSettings::setPortStr(const QString &port)
{
    m_strPort = port;
}


/*!
    \fn DlgCommSettings::setSpeedStr(const Qstring &speed)
 */
void DlgCommSettings::setSpeedStr(const QString &speed)
{
    m_strSpeed = speed;
}


/*!
    \fn DlgCommSettings::setStopBitsStr(const QString &stopBits)
 */
void DlgCommSettings::setStopBitsStr(const QString &stopBits)
{
    m_strStopBits = stopBits;
}
